import axios from "axios"

export default {
  namespaced:true,
  state:{
    list:[]
  },
  mutations:{
    updateList(state,list){
    state.list = list
    },
    updateCount(state,{id,count}){
      const item = state.list.find(item=>item.goods_id===id)
      if(item){
        item.goods_count = count
      }
    },
    updateState(state,{id,goods_state}){
      const item = state.list.find(item=>item.goods_id === id)
      if(item){
        item.goods_state =goods_state
      }
    },
    updateAllState(state,allState){
      state.list.forEach(item => {item.goods_state = allState});
    }
  },
  actions:{
    async getList(store){
      const res = await axios.get('https://applet-base-api-t.itheima.net/api/cart')
      store.commit('updateList',res.data.list)
    }
  },
  getters:{
    isAllChecked(state){
      return state.list.every(item => item.goods_state)
    },
    totalCount(state){
      let count = 0
      state.list.forEach(item=>{
        if(item.goods_state)count += item.goods_count
        
      })
      return count
    },
    totalPrice(state){
      let price = 0
      state.list.forEach(item=>{
        if(item.goods_state)price += item.goods_price * item.goods_count
        
      })
      return price
    }
  }
}